"""
A_star 2D
@author: huiming zhou
"""

import os
import sys
import math
import heapq

sys.path.append(os.path.dirname(os.path.abspath(__file__)) +
                "/../../Search_based_Planning/")

from Search_2D import plotting, env


class AStar:
    """
    AStar set the cost + heuristics as the priority
    """
    def __init__(self, s_start, s_goal, heuristic_type):
        self.s_start = s_start
        self.s_goal = s_goal
        self.heuristic_type = heuristic_type # 计算H值的方式

        self.Env = env.Env()  # class Env # 获取栅格地图

        self.u_set = self.Env.motions  # feasible input set  # 扩展当前节点的方向（新增禁止对角方向扩展，请大家看下运行结果的不同）
        self.obs = self.Env.obs  # position of obstacles # 障碍物的位置

        self.OPEN = []  # priority queue / OPEN set  openlist 对应文章的 开启列表
        self.CLOSED = []  # CLOSED set / VISITED order openlist 对应文章的 关闭列表
        self.PARENT = dict()  # recorded parent  字典，用于存放节点的父节点
        self.g = dict()  # cost to come 字典，用于存放节点的g值

    def searching(self):
        """
        A_star Searching.
        :return: path, visited order
        """
        """
        起点需要特殊处理
        起点的没有父节点，当然也可以按代码所写的，设置为起点本身
        起点的g值为0，因为g值是计算起点到当前点的代价，起点到起点的代价自然是0

        """       
        self.PARENT[self.s_start] = self.s_start
        self.g[self.s_start] = 0
        self.g[self.s_goal] = math.inf # 终点的G值设置成无穷大
        # heapq 堆 优先级队列
        # heappush 把 起点的F值 和 起点 压入堆中
        heapq.heappush(self.OPEN,
                       (self.f_value(self.s_start), self.s_start))

        # 当openlist不为空，如果openlist为空，表示无法找到可行路径，规划失败
        while self.OPEN: 
            _, s = heapq.heappop(self.OPEN) # 弹出open list中具有最小F值的节点坐标s
            self.CLOSED.append(s) # 把当前节点加入到close list

            # 如果当前节点是终点，表示找到可行路径，跳出循环
            if s == self.s_goal:  # stop condition
                break
        
            # 遍历当前点的邻居点    
            for s_n in self.get_neighbor(s):
                # 计算邻居点如果由当前点到达的新g值
                new_cost = self.g[s] + self.cost(s, s_n)

                # 如果邻居点从未被遍历过，则把g值设置成无穷大
                if s_n not in self.g:
                    self.g[s_n] = math.inf
                
                # 如果邻居点的新g值比之前的小，则
                if new_cost < self.g[s_n]:  # conditions for updating Cost
                    # 更新其G值
                    self.g[s_n] = new_cost
                    # 把邻居点的父节点设置为当前点
                    self.PARENT[s_n] = s
                    # 并加入到openlist中
                    heapq.heappush(self.OPEN, (self.f_value(s_n), s_n))

        return self.extract_path(self.PARENT), self.CLOSED

    def searching_repeated_astar(self, e):
        """
        repeated A*.
        :param e: weight of A*
        :return: path and visited order
        """

        path, visited = [], []

        while e >= 1:
            p_k, v_k = self.repeated_searching(self.s_start, self.s_goal, e)
            path.append(p_k)
            visited.append(v_k)
            e -= 0.5

        return path, visited

    def repeated_searching(self, s_start, s_goal, e):
        """
        run A* with weight e.
        :param s_start: starting state
        :param s_goal: goal state
        :param e: weight of a*
        :return: path and visited order.
        加入权重e，为了打破对称性，用于计算F值
        """

        g = {s_start: 0, s_goal: float("inf")}
        PARENT = {s_start: s_start}
        OPEN = []
        CLOSED = []
        heapq.heappush(OPEN,
                       (g[s_start] + e * self.heuristic(s_start), s_start))

        while OPEN:
            _, s = heapq.heappop(OPEN)
            CLOSED.append(s)

            if s == s_goal:
                break

            for s_n in self.get_neighbor(s):
                new_cost = g[s] + self.cost(s, s_n)

                if s_n not in g:
                    g[s_n] = math.inf

                if new_cost < g[s_n]:  # conditions for updating Cost
                    g[s_n] = new_cost
                    PARENT[s_n] = s
                    heapq.heappush(OPEN, (g[s_n] + e * self.heuristic(s_n), s_n))

        return self.extract_path(PARENT), CLOSED

    def get_neighbor(self, s):
        """
        find neighbors of state s that not in obstacles.
        :param s: state
        :return: neighbors
        获取扩展的邻居点
        """

        return [(s[0] + u[0], s[1] + u[1]) for u in self.u_set]

    def cost(self, s_start, s_goal):
        """
        Calculate Cost for this motion
        :param s_start: starting node
        :param s_goal: end node
        :return:  Cost for this motion
        :note: Cost function could be more complicate!
        计算邻居点到当前点的代价
        """

        if self.is_collision(s_start, s_goal):
            return math.inf

        # 相当于  sqrt(x*x + y*y)。
        return math.hypot(s_goal[0] - s_start[0], s_goal[1] - s_start[1])

    def is_collision(self, s_start, s_end):
        """
        check if the line segment (s_start, s_end) is collision.
        :param s_start: start node
        :param s_end: end node
        :return: True: is collision / False: not collision
        判断节点是否可通行
        """
        # 判断节点是否为障碍物
        if s_start in self.obs or s_end in self.obs:
            return True
        
        if s_start[0] != s_end[0] and s_start[1] != s_end[1]: # 当邻居点和当前点坐标一致时，忽略
            if s_end[0] - s_start[0] == s_start[1] - s_end[1]: # 对角线的邻居点
                s1 = (min(s_start[0], s_end[0]), min(s_start[1], s_end[1]))
                s2 = (max(s_start[0], s_end[0]), max(s_start[1], s_end[1]))
            else:
                s1 = (min(s_start[0], s_end[0]), max(s_start[1], s_end[1]))
                s2 = (max(s_start[0], s_end[0]), min(s_start[1], s_end[1]))
            
            # 判断邻居点是否为障碍物
            if s1 in self.obs or s2 in self.obs:
                return True

        return False

    def f_value(self, s):
        """
        f = g + h. (g: Cost to come, h: heuristic value)
        :param s: current state
        :return: f
        计算节点的F值  
        """

        return self.g[s] + self.heuristic(s)

    def extract_path(self, PARENT):
        """
        Extract the path based on the PARENT set.
        :return: The planning path
        通过节点的父节点，一步一步追溯到起点
        """
        # 先把终点坐标加入到path中
        path = [self.s_goal]
        s = self.s_goal

        while True:
            # 通过输入的坐标寻找该节点的父节点
            s = PARENT[s]
            # 把父节点坐标加入到path
            path.append(s)
            # 当坐标和起点坐标相同时，表示追溯完成
            if s == self.s_start:
                break

        return list(path)

    def heuristic(self, s):
        """
        Calculate heuristic.
        :param s: current node (state)
        :return: heuristic function value
        启发式函数 曼哈顿距离  dist = |X1-X2|+|Y1-Y2|
        启发式函数 欧式距离    两点直线距离
        """

        heuristic_type = self.heuristic_type  # heuristic type
        goal = self.s_goal  # goal node

        if heuristic_type == "manhattan": # 选择曼哈顿距离
            return abs(goal[0] - s[0]) + abs(goal[1] - s[1])
        else:
            return math.hypot(goal[0] - s[0], goal[1] - s[1])


def main():
    s_start = (5, 5)    #设置起点
    s_goal = (45, 25)   #设置终点
    # manhattan euclidean
    astar = AStar(s_start, s_goal, "euclidean") # 实例化
    plot = plotting.Plotting(s_start, s_goal)   # 标注起点和终点
    # path 表示找到的可行路径 
    # visited 表示遍历过的节点
    path, visited = astar.searching() # 进行A*算法
    plot.animation(path, visited, "A*")  # animation 动态展示

    # 以下注释部分只是多加了权重值 2.5 用于打破对称性
    # path, visited = astar.searching_repeated_astar(2.5)               # initial weight e = 2.5
    # plot.animation_ara_star(path, visited, "Repeated A*")


if __name__ == '__main__':
    main()
